import 'dart:math' show pi, sin, cos;
import 'package:app_core/app_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../common/constant/colors.dart';
import '../common/constant/styles.dart';


///flutter_smart_dialog的loading和toast的配置项
/// Loading 类型枚举
enum LoadingType {
  circular, // 圆形进度条（系统默认）
  dots, // 点点加载
  spinner, // 转轮加载（经典 iOS 样式）
}

/// Toast 类型枚举
enum ToastType {
  rounded, // 大圆角（默认）
  smallRounded, // 小圆角
  square, // 方角
  capsule, // 胶囊型（真正半圆角）
}

/// Loading 组件工厂
class LoadingWidgetFactory {
  // UI 配置常量
  static const double _loadingSize = 32.0;
  static const double _containerPadding = 16.0;
  static const double _containerRadius = 10.0;
  // static const double _containerOpacity = 0.85;
  static const double _textSize = 14.0;
  static const double _spacing = 10.0;
  static const Color _loadingColor = Colors.white;
  static const Color _textColor = Colors.white;
  static const Color _backgroundColor = Colors.black87;

  /// 根据类型创建 Loading Widget
  static Widget create(LoadingType type, String message) {
    switch (type) {
      case LoadingType.circular:
        return _buildCircularLoading(message);
      case LoadingType.dots:
        return _buildDotsLoading(message);
      case LoadingType.spinner:
        return _buildSpinnerLoading(message);
    }
  }

  // 通用容器
  static Widget _buildContainer({required Widget child}) {
    return Container(
      padding: const EdgeInsets.all(_containerPadding),
      decoration: BoxDecoration(color: _backgroundColor, borderRadius: BorderRadius.circular(_containerRadius)),
      child: child,
    );
  }

  // 通用文本
  static Widget _buildMessage(String msg) {
    if (msg.isEmpty) return const SizedBox.shrink();
    return Column(
      children: [const SizedBox(height: _spacing), Text(msg, style: const TextStyle(color: _textColor, fontSize: _textSize), textAlign: TextAlign.center)],
    );
  }

  // 圆形进度条（系统默认）
  static Widget _buildCircularLoading(String msg) {
    return _buildContainer(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: _loadingSize,
            height: _loadingSize,
            child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation<Color>(_loadingColor), strokeWidth: 3),
          ),
          _buildMessage(msg),
        ],
      ),
    );
  }

  // 点点加载
  static Widget _buildDotsLoading(String msg) {
    return _buildContainer(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [SizedBox(width: _loadingSize * 2, height: _loadingSize, child: _DotsIndicator(color: _loadingColor)), _buildMessage(msg)],
      ),
    );
  }

  // 转轮 loading（经典 iOS 样式）
  static Widget _buildSpinnerLoading(String msg) {
    return _buildContainer(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [SizedBox(width: _loadingSize, height: _loadingSize, child: _SpinnerIndicator(color: _loadingColor)), _buildMessage(msg)],
      ),
    );
  }
}

/// 点点指示器
class _DotsIndicator extends StatefulWidget {
  final Color color;

  const _DotsIndicator({required this.color});

  @override
  State<_DotsIndicator> createState() => _DotsIndicatorState();
}

class _DotsIndicatorState extends State<_DotsIndicator> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: const Duration(milliseconds: 1200), vsync: this)..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(3, (index) {
        return AnimatedBuilder(
          animation: _controller,
          builder: (context, child) {
            final delay = index * 0.2;
            final value = (_controller.value + delay) % 1.0;
            final opacity = (sin(value * pi * 2) * 0.5 + 0.5).clamp(0.3, 1.0);

            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 2),
              width: 6,
              height: 6,
              decoration: BoxDecoration(color: widget.color.withOpacity(opacity), shape: BoxShape.circle),
            );
          },
        );
      }),
    );
  }
}

/// 转轮指示器（经典 iOS 样式）
class _SpinnerIndicator extends StatefulWidget {
  final Color color;

  const _SpinnerIndicator({required this.color});

  @override
  State<_SpinnerIndicator> createState() => _SpinnerIndicatorState();
}

class _SpinnerIndicatorState extends State<_SpinnerIndicator> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(duration: const Duration(milliseconds: 1000), vsync: this)..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return CustomPaint(size: const Size(32, 32), painter: _SpinnerPainter(color: widget.color, animationValue: _controller.value));
      },
    );
  }
}

// 转轮画笔（经典 iOS 样式）
class _SpinnerPainter extends CustomPainter {
  final Color color;
  final double animationValue;

  _SpinnerPainter({required this.color, required this.animationValue});

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2.5; // 调整半径

    // 绘制 8 根短线条，经典 iOS 菊花样式
    for (int i = 0; i < 8; i++) {
      // 计算当前线条相对于动画的位置
      final normalizedIndex = (i + (animationValue * 8).floor()) % 8;
      final opacity = (8 - normalizedIndex) / 8.0 * 0.9 + 0.1; // 0.1 到 1.0 的透明度

      final paint =
          Paint()
            ..color = color.withOpacity(opacity)
            ..strokeWidth = 4.0
            ..strokeCap = StrokeCap.round;

      final angle = -(i * 45) * pi / 180; // 每 45 度一根线（8根线）
      final lineLength = radius * 0.4; // 线条长度

      // 线条从外圈向内圈
      final outerX = center.dx + radius * cos(angle);
      final outerY = center.dy + radius * sin(angle);
      final innerX = center.dx + (radius - lineLength) * cos(angle);
      final innerY = center.dy + (radius - lineLength) * sin(angle);

      canvas.drawLine(Offset(outerX, outerY), Offset(innerX, innerY), paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

///----------------------- Toast 组件工厂---------------------------
class ToastWidgetFactory {
  // UI 配置常量
  static const double _toastMinWidth = 80.0;
  static const double _toastMaxWidth = 240.0;
  static const double _toastPaddingH = 15.0;
  static const double _toastPaddingV = 14.0;
  static const double _toastTextSize = 15.0;
  static const Color _toastBackgroundColor = Colors.black87;
  static const Color _toastTextColor = Colors.white;
  static const double _iconSize = 24.0;
  static const double _iconTextSpacing = 8.0;

  static const double _iconToastBorderRadius = 10.0;

  /// 根据类型创建 Toast Widget
  static Widget create(ToastType type, String message, MsgType msgType) {
    switch (msgType) {
      case MsgType.success:
        return _buildToast(message, icon: Icons.check_circle, borderRadius: BorderRadius.circular(_iconToastBorderRadius));
      case MsgType.error:
        return _buildToast(message, icon: Icons.cancel, borderRadius: BorderRadius.circular(_iconToastBorderRadius));
      case MsgType.warning:
        return _buildToast(message, icon: Icons.info, borderRadius: BorderRadius.circular(_iconToastBorderRadius));
      default:
        return _buildToast(message, borderRadius: _getBorderRadius(type));
    }
  }

  /// 获取圆角半径
  static BorderRadius _getBorderRadius(ToastType type) {
    switch (type) {
      case ToastType.rounded:
        return BorderRadius.circular(20);
      case ToastType.smallRounded:
        return BorderRadius.circular(8);
      case ToastType.square:
        return BorderRadius.circular(4);
      case ToastType.capsule:
        return BorderRadius.circular(999);
    }
  }

  /// 统一的Toast构建方法
  static Widget _buildToast(String message, {IconData? icon, required BorderRadius borderRadius}) {
    return ConstrainedBox(
      constraints: BoxConstraints(minWidth: _toastMinWidth, maxWidth: _toastMaxWidth),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: _toastPaddingH, vertical: _toastPaddingV),
        decoration: BoxDecoration(color: _toastBackgroundColor, borderRadius: borderRadius),
        child:
            icon != null
                ? Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(icon, color: _toastTextColor, size: _iconSize),
                    SizedBox(height: _iconTextSpacing),
                    Text(message, style: TextStyle(color: _toastTextColor, fontSize: _toastTextSize, fontWeight: FontWeight.w400), textAlign: TextAlign.center),
                  ],
                )
                : Text(message, style: TextStyle(color: _toastTextColor, fontSize: _toastTextSize, fontWeight: FontWeight.w400), textAlign: TextAlign.center),
      ),
    );
  }
}

///----------------------- Notify 样式配置---------------------------
/// Notify 样式配置工厂
class NotifyStyleFactory {
  /// 创建 FlutterSmartNotifyStyle 配置
  static FlutterSmartNotifyStyle create() {
    return FlutterSmartNotifyStyle(
      successBuilder: (msg) => _buildStyleNotification(title: '成功', message: msg, icon: Icons.check_circle, backgroundColor: AppColor.success),
      failureBuilder: (msg) => _buildStyleNotification(title: '失败', message: msg, icon: Icons.cancel, backgroundColor: AppColor.error),
      warningBuilder: (msg) => _buildStyleNotification(title: '警告', message: msg, icon: Icons.warning, backgroundColor: AppColor.warning),
      alertBuilder: (msg) => _buildStyleNotification(title: '提醒', message: msg, icon: Icons.info, backgroundColor: AppColor.primary),
      errorBuilder: (msg) => _buildStyleNotification(title: '错误', message: msg, icon: Icons.error, backgroundColor: AppColor.error),
    );
  }

  /// iOS 风格的通知组件
  static Widget _buildStyleNotification({required String title, required String message, required IconData icon, required Color backgroundColor}) {
    return Container(
      margin: EdgeInsets.fromLTRB(16, ScreenAdapter.statusBarHeight, 16, 0),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(16),
        // boxShadow: [
        //   BoxShadow(
        //     color: Colors.black.withOpacity(0.1),
        //     blurRadius: 20,
        //     offset: const Offset(0, 8),
        //   ),
        // ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(14),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(color: AppColor.white.withOpacity(0.2), borderRadius: BorderRadius.circular(12)),
              child: Icon(icon, color: AppColor.white, size: 24),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(title, style: AppStyles.s16b.copyWith(color: AppColor.white)),
                  const SizedBox(height: 4),
                  Text(message, style: AppStyles.s14.copyWith(color: AppColor.white)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
